package com.itheima.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * 日期控制器类
 */
@Controller
public class DateController {
	/**
	 * 使用自定义类型数据绑定日期数据
	 */
	@RequestMapping("/customDate")
	public String CustomDate(Date date) {
	    System.out.println("date="+date);
	    return "success";
	}
	
	@RequestMapping("/customDate2")
	public String CustomDate2(Date date,Model model) {
	    System.out.println("date="+date);
		model.addAttribute("datedata",date);
	    return "success_date";
	}
	
	@RequestMapping("/question")
	public String CustomDate3(Date date,Model model,Integer addyear) {
			return "question";	
	}
	@RequestMapping("/answer")
	public String CustomDate4(Date date,Model model,Integer addyear) {
		//因为有表单提交要先验证参数是否有输入，即是否为空，如果为空，会发生嵌套异常错误
		if(date != null && addyear !=null) {
			//获取输入时间和年
		    System.out.println("date="+date);
			System.out.println("addyear="+addyear);
			//将时间转换成yyyy-MM-dd格式并返回给页面
			SimpleDateFormat ft1 = new SimpleDateFormat("yyyy/MM/dd");
			model.addAttribute("date",ft1.format(date));
			model.addAttribute("addyear",addyear);
			//获取输入时间的年并且将String转换成Integer类型
			SimpleDateFormat ft2 = new SimpleDateFormat("yyyy");
			String year1 = ft2.format(date);
			int year = Integer.parseInt(year1);
			//计算输入时间的年到要增加的年之间的天数
			addyear = year + addyear;
			int run = 0;
			int ping = 0;
			for (year += 1; year <= addyear; year++) {
				if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
					run += 1;
				} else {
					ping += 1;
				}
			}
			//将天数加入当前时间，先getTime+多出的时间，在setTime这一段
			long day = run * 366 + ping * 365;//添加时间一定要是长整型才能成功
			date.setTime(date.getTime() + day * 24 * 60 * 60 * 1000);
			//将时间换成那一天的星期输出，并返回到页面去
			String str = String.format(Locale.CHINESE, "%tA%n", date);
			System.out.println(str);
			model.addAttribute("str",str);
		    return "answer";
		}else {
			return "answer";
		}
	}
}
